var actbill = require('../../xc/model/diy_index')
var actbillpro = require('../../xc/model/pro_contents')
var syscart = require('../../xc/sys/cart')
var sys_databill = require('../../xc/model/sysdata')

Page({
  mixins: [require('../../xc/mixins/basicMixin')],
  /**
   * 页面的初始数据
   */
  data: {
    memberinfo: null,
    locationaddr: null,
    locationaddrtxt: "定位中...",
    diydata: null,
    themcolor: null,
    datasourcepara: {},
    pageloading: true,
    groupid: "",
    StatusBar: "",
    istop: false,
    xcpagesys: {},
    diypara: { //团长长参数
      clubid: 0, //团长
      diyid: 0,
    },
    cachecartinfo: {
      // cart:{},
      // groupcarnum:{pro:{}},
      // totalnum:

    },
    totalnuminfo: {},
    // groupcarnum:{
    //   pro:{},
    // }
    type: 0,
    customParams: encodeURIComponent(JSON.stringify({
      path: 'pages/index/index',
      pid: 1
    })),
    closePictureInPictureMode: 0,
    selected: {},
    cid: ""
  },
  xcloaddata: function (options, config) {



    this.setData({
      eg: config.eg
    })
    // return;
    var unit = "￥";
    if (config.yihuo && config.yihuo.status == 1) {
      unit = "∞"
    }
    this.setData({
      unit: unit
    })

    // console.log("xcloaddata")

    var app = getApp();
    //  console.log("xcloaddata")

    wx.getSystemInfo({
      success: function (res) {
        // console.log("rqqqqqqqqqqqqqqqqqqqqqqqqes")
        // console.log(res)
        // console.log(res['platform'])
        // console.log( app.globalData)
        app.globalData.platform = res['platform']

        // that.setData({
        //   platform: res['platform']
        // });
      }
    })


    var updatemodelfirst = {
      options
    };
    updatemodelfirst['config'] = config;
    if (config.home && config.home.usediv) {
      updatemodelfirst['usediv'] = config.home.usediv;
    } else {
      updatemodelfirst['usediv'] = 1;

    }
    if (config.prothem && config.prothem.popup) {
      updatemodelfirst["themcolor"] = config.prothem.config
      updatemodelfirst["popconfig"] = config.prothem.popup.proconfig
      updatemodelfirst["popCustomStyle"] = config.prothem.popup.customStyle
    }
    var diypara = this.data.diypara
    var diyparafield = ["clubid", "diyid"]
    diyparafield.forEach(function (field) {
      if (options[field]) {
        diypara[field] = options[field];
      }
    })




    updatemodelfirst["StatusBar"] = app.globalData.StatusBar
    updatemodelfirst["CustomBar"] = app.globalData.CustomBar
    updatemodelfirst["diypara"] = diypara;
    //diypara
    this.setData(updatemodelfirst)
    var diyid = 0;
    if (options && options.diyid) {

      diyid = options.diyid
    }
    var height = wx.getSystemInfoSync().windowHeight
    var that = this;

    actbill.diydata(diyid).then(function (reslutdata) {


      if (reslutdata && reslutdata["status"] == 1) {
        var nobj = reslutdata["obj"];

        diypara["diyid"] = nobj.id
        var upatemodel = {};
        upatemodel["diydata"] = JSON.parse(nobj["compilecontents"])
        console.log("diydata")
        console.log(upatemodel["diydata"])

        var body = upatemodel["diydata"]["body"]



        if (body) {
          var diytabproindex = 0;
          for (var a in body) {
            body[a]["strcsscuposit"] = that.secuposit(body[a]);
            if (!diytabproindex && body[a]['type'] == 'diytabpro') {
              diytabproindex = a
            }
          }

          if (config.yihuo && config.yihuo.status == 1 && body[diytabproindex] && body[diytabproindex]['type'] == 'diytabpro') {
            var clubpro = JSON.parse(JSON.stringify(body[diytabproindex]));
            clubpro['type'] = "diyclubpro";
            clubpro['main']['tabs']['isshow'] = -1;
            clubpro['main']['tabs']['tab']['css'] = "";
            clubpro['main']['tabs']['tab']['activecss'] = ""
            clubpro['main']['tabs']['css'] = ""

            clubpro['main']['loadmode'] = 3;
            clubpro['main']['imgdata']['condition']['num'] = 4
            upatemodel["clubproobj"] = clubpro
            upatemodel["clubproindex"] = diytabproindex - 1

          }

        }

        //  nobj["datasourcepara"]['7']=nobj["datasourcepara"]['6']
        upatemodel["datasourcepara"] = nobj["datasourcepara"]
        upatemodel["pageloading"] = false

        upatemodel["diypara"] = diypara;


        console.log("upatemodel")
        console.log(upatemodel)

        // return

        that.setData(upatemodel)


        that.loadpagesys();
        wx.createIntersectionObserver().relativeToViewport({
          bottom: -(height - 50)
        }).observe('.diytabprocom', (res) => {
          if (res.intersectionRatio == 0) {
            that.setData({
              istop: false
            })
          } else {
            that.setData({
              istop: true
            })
          }
        })

        if (that.selectComponent("#chiefcomv")) {

          that.selectComponent("#chiefcomv").init()
        }

      }
    })

    if (config.home.taskbuystatus == 1) {
      this.getactindex()

    }
    if (config.yihuo && config.yihuo.status == 1) {

      this.getprolist();
    }
    this.loadcartinfo()
  },
  getClubInfo(ev) {

    var cid = ""
    if (ev.detail && ev.detail.id) {

      if (ev.detail.cid) {
        cid = ev.detail.cid
      } else {
        cid = 1
      }

    }

    this.setData({
      cid: cid
    })
  },
  aftergetaddr(ev) {

    if (this.selectComponent("#chiefcomv")) {
      this.selectComponent("#chiefcomv").init()
    }
  },
  getprolist() {
    var that = this;
    var condition = {
      protype: 2,
      status: 1
    }
    actbillpro.getprolist(condition).then(function (result) {
      console.log("result")
      console.log(result)
      if (result['status'] == 1) {
        var obj = {
          data: result['obj']
        }
        that.setData({
          clubpro: obj
        })
      }

    })
  },
  onLoad: function (options) {

  },
  agree(e) {
    // 用户点击同意按钮后
    this.resolvePrivacyAuthorization({
      buttonId: 'agree-btn',
      event: 'agree'
    })
  },
  disagree(e) {
    this.resolvePrivacyAuthorization({
      event: 'disagree'
    })
  },
  afterlogin(ev, config, userinfo) {



    // return;

    this.setData({
      member: userinfo
    })

    if (userinfo["memberinfo"]) {

      this.setData({
        memberinfo: userinfo["memberinfo"]
      })

      this.maketip(config);
    }

    this.selectComponent("#advertise").init();

    this.selectComponent("#xcpopup").sysinit(userinfo['id']);




  },
  // 加购成功事件
  aftercart(e) {

    this.selectComponent("#footer").loadcardlength()
  },
  buyactvitypro(e) {

    var activity = e.detail.activity;
    //活动未开始/结束/下架不能购买 达到上限
    if ((!activity) || activity.actstatus != 1) {
      wx.showToast({
        icon: "none",
        title: '活动失效',
      })
      return;
    }


    var that = this
    var option = {
      aid: activity.id,
      atype: activity.itype
    }
    var proid = e.detail.proid;

    actbillpro.showattrchose(that, proid, that.data.selected[proid], activity.itype == 3 ? 2 : 3, option)
  },
  getactindex() {

    var that = this
    actbillpro.getindexactivity().then(res => {
      if (res['status'] == 1) {
        console.log("getactindex")
        if (res['obj'] && res['obj'][0] && that.selectComponent("#taskactivity")) {
          that.selectComponent("#taskactivity").init(res['obj'][0]['id'])
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  changelocation(ev) {
    var topnav = this.selectComponent("#topnav");
    if (topnav) {
      topnav.updatedata()
    }
  },

  maketip(config) {
    var that = this;
    if (config.task && config.task.indextipstatus == 1) {
      // wx.setStorage({
      //   key: "value",
      //   data: e.currentTarget.dataset.num3,
      //   encrypt: true, // 若开启加密存储，setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
      //   success() {
      //   }
      // })
      wx.getStorage({
        key: "taskpop",
        encrypt: false, // 若开启加密存储，setStorage 和 getStorage 需要同时声明 encrypt 的值为 true
        success(res) {
          var date = that.getnowdate()
          console.log("sssssssssssssssss")

          console.log(date)
          console.log(res.data)

          if (res.data != date) {
            that.gettips(config)

          }
        },
        fail(res) {
          that.gettips(config)

        }
      })
      // 
    }
  },
  //任务团 余额将即将转化提醒
  gettips(config) {
    var that = this;
    sys_databill.gettips().then(res => {
      console.log("ddddddddddd")
      console.log(res)

      if (res["status"] == 1) {
        var obj = res["obj"];
        if (obj > 0) {
          var data = {}
          var taskconfig = config.task
          data['title'] = taskconfig.indexpopuptitle;
          var indexpopup = taskconfig.indexpopup;
          indexpopup = indexpopup.replace("xx", obj)

          data['contents'] = indexpopup;
          that.selectComponent("#xcpopup").init(data);

          var date = that.getnowdate()
          wx.setStorage({
            key: "taskpop",
            data: date,
            encrypt: false,
            success() {

            }
          })
        }
      }
    })
  },
  getnowdate() {
    var myDate = new Date();
    var y = myDate.getFullYear();
    var m = myDate.getMonth() + 1;
    var d = myDate.getDate() < 10;
    return y + '-' + this.addzero(m) + '-' + this.addzero(d)
  },
  addzero(d) {
    if (d < 10) {
      d = '0' + d
    }
    return d
  },
  navclick(ev) {
    var locationseachaddr = this.selectComponent("#locationseachaddr");
    if (locationseachaddr) {
      locationseachaddr.show();
    }
  },
  cartop(ev) {
    // var opmodel={item:pro,op:"add",num:1}
    var detail = ev.detail
    var that = this;
    switch (detail.op) {
      case "reload": {
        that.loadcartinfo();
        //
        break;
      }
    }
  },
  clubprobuy(ev) {
    console.log("ev")
    console.log(ev)
    var item = ev.detail.dataset.item
    var that = this
    // var option = {protype:2}; //团长产品
    var option = {
      protype: 2,
      clubid: item.shopid,
      clubmode: item.autarky == 1 ? '4' : '2'
    }; //团长产品

    actbillpro.showattrchose(that, item.id, that.data.selected, 2, option)

  },
  buy(ev) {
    var that = this
    var dataset = ev.detail.dataset
    var item = dataset.item
    var option = {};
    var optionfileds = ["atype", "aid"];
    optionfileds.forEach(atrrkey => {
      if (dataset.hasOwnProperty(atrrkey)) {
        option[atrrkey] = dataset[atrrkey]
      }
    })
    // 1加购 2立即购买 3两种
    actbillpro.showattrchose(that, item.id, null, 3, option)
  },
  //
  gettop(topset) {
    var app = getApp();
    if (topset == "1") {
      //标签距离
      return (app.globalData.CustomBar - 2)
    } else if (topset == "2") {
      //到顶部的距离
      return app.globalData.Custom.top;
    }
    return 0;
  },

  //特殊处理定位
  secuposit(obj) {
    var that = this;
    if (obj && obj["css"]) {
      if (obj["csscuposit"]) {
        var csscuposit = obj["csscuposit"]
        var strcsscuposit = []
        strcsscuposit.push("position:" + csscuposit["position"])
        strcsscuposit.push("z-index:" + csscuposit["z-index"])
        var allowfield = ["top", "left", "right", "bottom"];
        var sizeunit = csscuposit["pos"].sizeunit;
        var pos = csscuposit["pos"]
        allowfield.forEach(item => {
          if (pos[item]) {
            if (item == "top") {
              var xval = that.gettop(csscuposit["topset"])
              if (xval) {
                strcsscuposit.push(item + ":" + "calc(" + xval + "px + " + pos[item].val + sizeunit + ")")
              }

            } else {
              strcsscuposit.push(item + ":" + pos[item].val + sizeunit)
            }
          }
        })
        return ";" + strcsscuposit.join(";");
      }
    }
    return ""
  },

  loadpagesys() {
    var that = this;
    //xcpagesys
    setTimeout(() => {
      wx.createSelectorQuery().selectAll('#footer').boundingClientRect(function (rect) {
        var temupdate = {};
        temupdate["xcpagesys.foot"] = rect[0];

        that.setData(temupdate);
      }).exec()

    }, 500);
  },

  setpage(selector) {

    wx.pageScrollTo({
      selector: ".diytabprocom",
      duration: 300,
    })
  },

  onClickLeft() {
    wx.showToast({
      title: '点击返回',
      icon: 'none'
    });
  },
  onClickRight() {
    wx.showToast({
      title: '点击按钮',
      icon: 'none'
    });
  },
  loadcartinfo() {
    var that = this

    syscart.loadcartlocal().then(function name(resobj) {
      that.setData({
        cachecartinfo: resobj,
        totalnuminfo: resobj["totalnuminfo"]
      })
    })


    if (this.selectComponent("#footer")) {
      this.selectComponent("#footer").loadcardlength()

    }

  },
  cartclosed() {
    var that = this
    that.loadcartinfo()
  },

  cartsumbit() {
    // 提交购买车订单
    var app = getApp();
    var chiefcomv = this.selectComponent("#chiefcomv")
    if (chiefcomv) {
      var addrinfo = chiefcomv.getaddrinfo();

      app.globalData.temcart["addrinfo"] = addrinfo



    } else {
      app.globalData.temcart["addrinfo"] = null
    }





    wx.navigateTo({
      url: '/' + app.globalData.xcsys.m + '/shop/paycore/payinfo?iscart=1&hasaddr=1'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  backtop() {
    wx.pageScrollTo({
      scrollTop: 0
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loadcartinfo()
    // 版本自动更新代码
    const updateManager = wx.getUpdateManager()
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新检测',
        content: '检测到新版本，是否重启小程序？',
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })
    updateManager.onUpdateFailed(function () {
      // 新的版本下载失败
      wx.showModal({
        title: '已有新版本咯',
        content: '请您删除当前小程序，重新打开呦~',
        showCancel: false
      })
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // var diytabprocom = this.selectComponent(".diytabprocom").selectAllComponents()
    console.log("onReachBottom")
    console.log(this.data.config)
    if (this.data.usediv == 1 && this.data.config.jtklmapi && this.data.config.jtklmapi.status == 1 && this.data.config.jtklmapi.showpro && this.data.config.jtklmapi.showpro == 1) {
      this.selectComponent("#jtk").onReachBottom()
    }
    if (this.data.usediv == 1 && this.data.config.home && this.data.config.home.taskbuystatus == 1) {
      this.selectComponent("#taskactivity").onReachBottom()
    } else {
      var diytabprocoms = this.selectAllComponents(".diytabprocom")
      // var diytabprocoms =SelectorQuery.selectAll(".diytabprocom")
      console.log("ffffffffffff")

      console.log(diytabprocoms)
      // console.log(diytabprocoms)
      for (var i in diytabprocoms) {
        var diytabprocom = diytabprocoms[i];
        console.log("xxxxxxxxxxxxxxxx")

        console.log(diytabprocom)
        if (diytabprocom) {
          diytabprocom.pagebottom()
        }
      }
    }
  },
})